import json
import os
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


def  _save_collected_data_to_file(ticker: str, collected_data: dict, filename: str):
        """
        将收集的数据保存到本地文件

        Args:
            ticker: 股票代码
            collected_data: 收集的数据
        """
        import json
        import os
        from datetime import datetime

        try:
            if not collected_data:
                logger.warning(f"股票 {ticker} 没有收集到数据，跳过保存")
                return

            # 创建数据目录
            data_dir = "data/collected_data"
            if not os.path.exists(data_dir):
                os.makedirs(data_dir)

            # latest_filename = f"market_data_agent_data_{ticker}_latest.json"
            latest_file_path = os.path.join(data_dir, filename)
            with open(latest_file_path, "w", encoding="utf-8") as f:
                json.dump(collected_data, f, ensure_ascii=False, indent=2, default=str)

            print(f"✅ 最新数据已保存到: {latest_file_path}")

        except Exception as e:
            error_msg = f"保存数据到文件失败: {str(e)}"
            logger.error(error_msg)
            print(f"❌ {error_msg}")